//
//  SNKPhotoViewController.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/8.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKPhotoViewController.h"
#import "UIBarButtonItem+SNK.h"
#import "SNKWaterFlowLayout.h"
#import "SNKPhotoCell.h"
#import "KDJHttpTool.h"
#import "SNKImg.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "PullDownView.h"
#import "SNKPhotoShowViewController.h"
#import <DKNightVersion.h>

@interface SNKPhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic , strong) NSString *            degreeName;
@property (nonatomic , copy) NSString *              tagLever1;
@property (nonatomic , copy) NSString *              tagLever2;
@property (nonatomic , weak) UICollectionView *      collectionView;
@property (nonatomic , assign) int                   startIndex;
@property (nonatomic , strong) NSMutableArray *      imgsObjectArray;
@property (nonatomic , strong) PullDownView *        pullDownView;
@property (nonatomic , strong) NSArray *             classArray;

@end

@implementation SNKPhotoViewController

static NSString *const ID = @"photo";

#pragma mark - 懒加载
- (NSMutableArray *)imgsObjectArray{
    if (!_imgsObjectArray) {
        _imgsObjectArray = [NSMutableArray array];
    }
    return _imgsObjectArray;
}

- (NSArray *)classArray {
    if (!_classArray) {
        _classArray = @[
                        [PullDownItem itemWithTitle:@"精选" icon:[UIImage imageNamed:@"mingxing"]],
                        [PullDownItem itemWithTitle:@"明星" icon:[UIImage imageNamed:@"meinvchannel"]],
                        [PullDownItem itemWithTitle:@"汽车" icon:[UIImage imageNamed:@"qiche"]],
                        [PullDownItem itemWithTitle:@"宠物" icon:[UIImage imageNamed:@"chongwu"]],
                        [PullDownItem itemWithTitle:@"动漫" icon:[UIImage imageNamed:@"dongman"]],
                        [PullDownItem itemWithTitle:@"设计" icon:[UIImage imageNamed:@"sheji"]],
                        [PullDownItem itemWithTitle:@"家居" icon:[UIImage imageNamed:@"jiaju"]],
                        [PullDownItem itemWithTitle:@"婚嫁" icon:[UIImage imageNamed:@"hunjia"]],
                        [PullDownItem itemWithTitle:@"摄影" icon:[UIImage imageNamed:@"sheying"]],
                        [PullDownItem itemWithTitle:@"美食" icon:[UIImage imageNamed:@"meishi"]]
                        ];
    }
    return _classArray;
}

// 懒加载下拉控件
- (PullDownView *)pullDownView
{
    if (!_pullDownView) {
        _pullDownView = [[PullDownView alloc]init];
        [_pullDownView setDataWithItemAry:self.classArray];
    }
    IMP_BLOCK_SELF(SNKPhotoViewController);
    _pullDownView.SelectBlock = ^(id selTitle){
        block_self.degreeName = selTitle;
        block_self.navigationItem.rightBarButtonItem = [UIBarButtonItem navigationBarRightButtonItemWithTitleAndImage:[UIImage imageNamed:@"arrow_down"]
                                                                                                                Title:selTitle
                                                                                                               Target:block_self
                                                                                                             Selector:@selector(openMenu)
                                                                                                           titleColor:[UIColor whiteColor]];
        [block_self.collectionView setContentOffset:CGPointMake(0, -64) animated:NO];
        block_self.startIndex = 0;
        block_self.tagLever1 = selTitle;
        block_self.tagLever2 = @"全部";
        [block_self.collectionView.mj_header beginRefreshing];
    };
    _pullDownView.removeBlock = ^{
        block_self.navigationItem.rightBarButtonItem = [UIBarButtonItem navigationBarRightButtonItemWithTitleAndImage:[UIImage imageNamed:@"arrow_down"]
                                                                                                                Title:block_self.degreeName
                                                                                                               Target:block_self
                                                                                                             Selector:@selector(openMenu)
                                                                                                           titleColor:[UIColor whiteColor]];
    };
    return _pullDownView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 就是这一块,出问题了,用了新的框架,通知可能会重复
    // 监听刷新通知,
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(mynotification) name:self.title object:nil];
    
    // 去掉顶部title
//    self.title = @"菠萝蜜";
    
    // 右边按钮
    self.degreeName = @"精选";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem navigationBarRightButtonItemWithTitleAndImage:[UIImage imageNamed:@"arrow_down"] Title:self.degreeName Target:self Selector:@selector(openMenu) titleColor:[UIColor whiteColor]];
    
    // 设置一级二级tag
    self.tagLever1 = @"美女";
    self.tagLever2 = @"可爱";
    // 设置collection
    [self setupCollection];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)mynotification
{
    [self.collectionView.mj_header beginRefreshing];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

// 点击展开按钮
- (void)openMenu {
    if (self.pullDownView.isShow) {
        [self.pullDownView removeView];
    } else {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem navigationBarRightButtonItemWithTitleAndImage:[UIImage imageNamed:@"arrow_up"] Title:self.degreeName Target:self Selector:@selector(openMenu) titleColor:HEXColor(@"333333")];
        [self.pullDownView show];
    }
}

// 设置collectionView
- (void)setupCollection {
    IMP_BLOCK_SELF(SNKPhotoViewController);
    
    // 自定义瀑布流layout
    SNKWaterFlowLayout *layout = [[SNKWaterFlowLayout alloc] init];
    // 计算cell高度的Block
    layout.HeightBlock = ^CGFloat(CGFloat sender, NSIndexPath *index){
        SNKImg *img = block_self.imgsObjectArray[index.item];
        return img.small_height / img.small_width * sender;
    };
    layout.columnsCount = 2;
    
    // 设置CollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    // 颜色相关
    collectionView.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    // 注册PhotoCell
    [collectionView registerNib:[UINib nibWithNibName:@"SNKPhotoCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
    // 添加collectionView
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    // 设置下拉控件
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        block_self.startIndex = 0;
        [block_self loadData];
    }];
    self.collectionView.mj_header = header;
    [header beginRefreshing];
    
    // 设置上拉控件
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [block_self loadMoreData];
    }];
}

- (void)loadData {
    IMP_BLOCK_SELF(SNKPhotoViewController);
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    parameters[@"pn"] = [NSString stringWithFormat:@"%d",self.startIndex];
    parameters[@"rn"] = @60;
    
    NSString *urlStr = [NSString stringWithFormat:@"http://image.baidu.com/wisebrowse/data?tag1=%@&tag2=%@",self.tagLever1,self.tagLever2];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[KDJHttpTool shareHttpTool] runRequestWithParameters:parameters path:urlStr success:^(id responseObject) {
        // 字典转实体
        NSMutableArray *imgsObjectArray = [SNKImg mj_objectArrayWithKeyValuesArray:responseObject[@"imgs"]];
        // 存放数据
        block_self.imgsObjectArray = imgsObjectArray;
        // 所有加60
        block_self.startIndex += 60;
        // 刷新collectionView
        [block_self.collectionView reloadData];
        
        [block_self.collectionView.mj_header endRefreshing];
        [block_self.collectionView.mj_footer endRefreshing];
        
    } failure:^(id error) {
        
        [block_self.collectionView.mj_header endRefreshing];
        [block_self.collectionView.mj_footer endRefreshing];
        
    }];
}

- (void)loadMoreData {
    IMP_BLOCK_SELF(SNKPhotoViewController);
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", self.startIndex];
    parameters[@"rn"] = @60;
    
    NSString *urlStr = [NSString stringWithFormat:@"http://image.baidu.com/wisebrowse/data?tag1=%@&tag2=%@",self.tagLever1,self.tagLever2];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[KDJHttpTool shareHttpTool] runRequestWithParameters:parameters path:urlStr success:^(id responseObject) {
        // 字典转实体
        NSMutableArray *imgsObjectArray = [SNKImg mj_objectArrayWithKeyValuesArray:responseObject[@"imgs"]];
        [block_self.imgsObjectArray addObjectsFromArray:imgsObjectArray];
        
        block_self.startIndex += 60;
        block_self.collectionView.mj_footer.hidden = block_self.imgsObjectArray.count < 60;
        [block_self.collectionView reloadData];
        
        [block_self.collectionView.mj_header endRefreshing];
        [block_self.collectionView.mj_footer endRefreshing];
        
    } failure:^(id error) {
        
        [block_self.collectionView.mj_header endRefreshing];
        [block_self.collectionView.mj_footer endRefreshing];
        
    }];
}

#pragma mark - UICollectionView数据源和代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imgsObjectArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SNKPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.img = self.imgsObjectArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SNKPhotoShowViewController *photoShow = [[SNKPhotoShowViewController alloc] init];
    photoShow.currentIndex = (int)indexPath.row;
    photoShow.mutaArray = self.imgsObjectArray;
    [self.navigationController pushViewController:photoShow animated:YES];
}

@end
